package com.dragon.web.commons.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dragon.web.commons.constant.ErrorCode;
import com.dragon.web.commons.filter.CorsFilter;
import com.dragon.web.commons.utils.FileUtils;
import com.dragon.web.commons.utils.ImageUtils;
import com.dragon.web.commons.vo.FintechResult;
import com.marvels.common.utils.MarvelsLogUtil;


@Controller
@RequestMapping("${platform.name.code}/file")
public class FileController {
	
	@ResponseBody
	@RequestMapping(value = "/upload/ic")
	public FintechResult upload(MultipartFile file ,HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			 MarvelsLogUtil.getInstance().info(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------  file = " + file);
			// 限制文件的类型，文件的大小 TODO
			String prefix = FileUtils.getPathPrefix();
			String uuid = UUID.randomUUID().toString();
			String nfsFileSystem = FileUtils.getValueByPropertiesKey("nfs.file.system"); // 服务器地址
			String path = nfsFileSystem + prefix;
			String fileName = file.getOriginalFilename();
			try {
				fileName = "idCard_" + uuid + fileName.substring(fileName.lastIndexOf("."), fileName.length());
			} catch (Exception e1) {
				fileName = "idCard_" + uuid + fileName + ".png";
			}
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// springboot 是用这种方式会存在上传问题
			//file.transferTo(targetFile);
			String filePath = path + File.separator + fileName;
			MarvelsLogUtil.getInstance().info("上传路径：" + filePath);
			File tempFile = new File(filePath);
			org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
			
			// 保存缩咯图
			String bigPath = path + "/" + fileName;
			ImageUtils.thumbnailImage2(new File(bigPath), 200, 200, "small_", false);
			resultMap.put("smallPath", nfsFileSystem + prefix.toString() + "/" + "small_" + fileName);
			resultMap.put("path", nfsFileSystem + prefix.toString() + "/" + fileName);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------  file = " + file, e);
			return FintechResult.getResult(ErrorCode.FAIL, "上传失败", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}
	
}
